package cn.com.yang.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 计数器闭锁
 * @author 杨亿金
 * @date 2022年8月31日-下午7:49:35
 * @since 1.0.0
 */
public class TestCountDownLatch {
	private final static int threadCount = 200;
	
	public static void main(String[] args) throws InterruptedException {
		ExecutorService exec = Executors.newCachedThreadPool();
		final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
		for (int i = 0; i < threadCount; i++) {
			final int threadNum = i;
			exec.execute(()->{
				try {
					test(threadNum);
				} catch (Exception e) {
					e.printStackTrace();
				}finally {
					countDownLatch.countDown();//计数器减一
				}
			});
		}
		countDownLatch.await();
		//countDownLatch.await(10, TimeUnit.MILLISECONDS);
		System.out.println("finish");
		exec.shutdown();
	}

	private static void test(int threadNum) throws InterruptedException {
		Thread.sleep(100);
		System.out.println("finish");
		Thread.sleep(100);
	}
}
